﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace WebApplication1.TestThread.TestTask
{
    /// <summary>
    /// Handler 的摘要说明
    /// </summary>
    public class Handler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //获取图片名，把图片数量写OutputStream
            List<String> urlList = (List<string>)context.Application["Url"];
            context.Response.OutputStream.Write(BitConverter.GetBytes(urlList.Count), 0, 4);

            //把图片转换成二进制数据
            List<string> imageList = GetImages(urlList);

            //把每副图片长度写入OutputStream
            foreach (string image in imageList)
            {
                byte[] imageByte = Convert.FromBase64String(image);
                context.Response.OutputStream.Write(BitConverter.GetBytes(imageByte.Length), 0, 4);
            }

            //把图片写入OutputStream
            foreach (string image in imageList)
            {
                byte[] imageByte = Convert.FromBase64String(image);
                context.Response.OutputStream.Write(imageByte, 0, imageByte.Length);
            }
        }

        //获取多个图片的二进制数据
        private List<string> GetImages(List<string> urlList)
        {
            List<string> imageList = new List<string>();
            foreach (string url in urlList)
                imageList.Add(GetImage(url));
            return imageList;
        }

        //获取单副图片的二进制数据
        private string GetImage(string url)
        {
            string path = "F:/Documents and Settings/Administrator/桌面/TemLib/测试/Solution1/WebApplication1/Images/" + url;
            FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] imgBytes = new byte[10240];
            int imgLength = stream.Read(imgBytes, 0, 10240);
            return Convert.ToBase64String(imgBytes, 0, imgLength);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}